import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useParams } from 'react-router-dom'
import styles from './index.module.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { Channel } from '@/components/Channel'
import { useState, useRef, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router'
import { updateArticle, getArticleById } from '@/store/actions'
const Publish = () => {
  const [fileList, setFileList] = useState([])
  const [maxCont, setMaxCont] = useState(1)
  const fileListRef = useRef([])
  const dispatch = useDispatch()
  const history = useHistory()
  const [form] = Form.useForm()
  // 上传封面
  const onUploadChange = (info) => {
    const fileList = info.fileList.map((file) => {
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      return file
    })
    setFileList(fileList)
    // 上传图片时，将所有图片存储到 ref 中
    fileListRef.current = fileList
  }
  // 控制封面数量
  const changeType = (e) => {
    const count = e.target.value
    setMaxCont(count)

    if (count === 1) {
      // 单图，只展示第一张
      const firstImg = fileListRef.current[0]
      setFileList(firstImg === undefined ? [] : [firstImg])
    } else if (count === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current)
    }
  }
  // 封装发布或编辑
  const saveArticle = async (value, msg, isDraft) => {
    if (value.type !== fileList.length)
      return message.warning('封面数量与所选类型不匹配')

    const { type, ...rest } = value
    const data = {
      ...rest,
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    }
    if (isEdit) {
      data.id = id
    }
    try {
      await dispatch(updateArticle(data, isDraft, isEdit))
      message.success(msg, 1, () => {
        history.replace('/home/article')
      })
    } catch (e) {}
  }
  // 添加数据
  const onFinish = async (value) => {
    try {
      saveArticle(value, isEdit ? '编辑成功' : '发表成功', false)
    } catch (e) {}
  }
  // 添加草稿
  const saveDraft = async () => {
    console.log(111)
    try {
      const value = await form.validateFields()
      console.log(value)
      saveArticle(value, '添加草稿成功', true)
    } catch (e) {
      console.log(e)
    }
  }
  const { id } = useParams()
  const isEdit = id !== undefined
  // 编辑回显数据
  useEffect(() => {
    const loadData = async () => {
      if (!isEdit) return
      try {
        const res = await dispatch(getArticleById(id))
        const { images, ...formValue } = res
        form.setFieldsValue(formValue)
        const imageList = images.map((item) => ({ url: item }))
        setFileList(imageList)
        setMaxCont(formValue.type)
        fileListRef.current = imageList
      } catch (e) {
        message.warning('错误')
      }
    }
    loadData()
  }, [form, id, dispatch, isEdit])
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ content: '', type: 1 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            {/* <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              <Option value={0}>推荐</Option>
            </Select> */}
            <Channel width={400} />
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {maxCont > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                multiple={maxCont > 1}
                maxCount={maxCont}
                fileList={fileList}
                onChange={onUploadChange}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '修改文章' : '发布文章'}
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
